/**
 * Copyright 2015-2048 Kiss Baby Group Holding Ltd.
 */
package drds.server.net;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ConcurrentLinkedQueue;

import drds.server.config.Versions;
import drds.server.net.packet.ShakeHandPacket;
import drds.server.net.packet.auth.AuthRequestPacket;
import drds.server.net.packet.auth.AuthResponsePacket;
import drds.server.net.packet.auth.HmacMD5;
import drds.server.server.SessionContext;

public class AuthThread implements Runnable {
	public final static ConcurrentLinkedQueue<SocketChannel> registerQueue = new ConcurrentLinkedQueue<SocketChannel>();

	public void run() {
		registerQueue.clear();
		while (true) {
			SocketChannel socketChannel = registerQueue.poll();
			try {

				byte[] seed = HmacMD5.initKey();
				// 发送握手数据包
				ShakeHandPacket shakeHandPacket = new ShakeHandPacket();
				shakeHandPacket.packetId = 0;
				shakeHandPacket.protocolVersion = Versions.PROTOCOL_VERSION;
				shakeHandPacket.serverVersion = Versions.SERVER_VERSION;
				shakeHandPacket.sessionContextId = 0;
				shakeHandPacket.seed = seed;
				shakeHandPacket.write();

				byte[] password = "".getBytes();
				// 在这里读取数据
				validator(socketChannel, seed, password);

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void validator(SocketChannel socketChannel, byte[] seed, byte[] password) throws IOException {
		ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
		socketChannel.read(byteBuffer);
		AuthRequestPacket authPacket = new AuthRequestPacket();
		authPacket.read(byteBuffer.array());

		AuthResponsePacket authResultPacket = new AuthResponsePacket();
		String database = authPacket.database;
		String userName = authPacket.userName;

		password = HmacMD5.encode(seed, password);
		if (database != null) {
			authResultPacket.error((byte) 1);
			quit("");
			return;
		}
		if (userName != null) {
			authResultPacket.error((byte) 2);
			quit("");
			return;
		}
		if (password != authPacket.password) {
			//
			authResultPacket.error((byte) 2);
			quit("");
			return;
		} else {
			authResultPacket.ok();
			// 建立
			//
			SessionContext sessionContext = (SessionContext) SessionContextFactory.make(socketChannel);
			sessionContext.init();
		}
	}

	private void quit(String string) {

	}

}
